#!/usr/bin/env python
# -*- coding: utf-8 -*- 

#Kiwi Bot
#Make by @nge1nCorsic4 in 2011
#Modified by @nge1nCorsic4 in 2012
#This program is free software; you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation; either version 2 of the License, or
#(at your option) any later version.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License along
#with this program; if not, write to the Free Software Foundation, Inc.,
#51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import kiwi
import os, urllib2

class Update:
	def __init__(self, main):
		self.main = main
	def request(self,page):
		req = urllib2.Request(page)
		handle = urllib2.urlopen(req)
		return handle.read()
	def update(self):
		repo = 'http://clan-fun.fr/depot/kiwi_V3_Alpha/'
		fullPath = os.path.split(os.path.dirname(os.path.abspath(__file__)))[0]+'/'
		slash = os.sep
		try:
			list = 'list_noconf.txt'
			liste = self.request(repo + list)
		except urllib2.HTTPError:
			self.main.log.warn('erreur de connection au depot')
		liste = liste.split(';')
		maj = ''
		for i in liste:
			i = i.strip()
			if '\\' in i:
				path = i.split('\\')
				cp = ''
				for p in path[:-1]:
					cp += p+slash
					if os.path.isdir(fullPath+cp) == False:
						os.mkdir(fullPath+cp)
			try:
				i = i.replace('\\','/')
				content = self.request(repo+i)
				if os.name == 'nt' :
					i = i.replace('/',slash)
				if os.path.isfile(fullPath+i):
					f = file(fullPath+i,'r')
					data = f.read()
					f.close()
					if content == data:
						continue
				f = file(fullPath+i,'w')
				f.write(content)
				f.close()
				maj += '^3%s^1, '%i
			except urllib2.HTTPError:
				self.main.log.warn('erreur de connection au depot')
			except IOError:
				self.main.log.warn('Erreur lors de l\'ecriture du fichier %s. Il est probable que vous n\'ayez pas les droits d\'ecriture dans le dossier choisi.'%(i))
		return maj